package com.qtest.qandroid.controller;

import com.qtest.qandroid.entity.*;
import com.qtest.qandroid.service.UserService;
import com.qtest.qandroid.util.gpsDistance;
import com.qtest.qandroid.util.timecha;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author Yu
 * @time 2019/11/25 14:22
 */

@RestController
public class UserController {

    @Autowired
    private UserService userService;
    private Date da;
    private User user;
    private AttendanceJob attendanceJob;
    private Course course;

    @RequestMapping(value = "query",method = RequestMethod.GET)
    public String q(){
        return "123";
    }

    /**
     * 测试
     *
     * */
    @RequestMapping(value = "queryByName",method = RequestMethod.POST)
    public Result<AttendanceRecord> queryByNAme(@RequestBody JSONObject s){
        JSONObject js = JSONObject.fromObject(s);
        String record = js.getString("number");
        Result<AttendanceRecord> result = new Result<>();
        result.setData(userService.queryByName(record));
        return result;
    }

    /**
     * 用户登录
     *
     * */
    @RequestMapping(value = "login",method = RequestMethod.POST)
    public Result<String> login(@RequestBody JSONObject s) {
        JSONObject js = JSONObject.fromObject(s);
        String userId = js.getString("userId");
        String password = js.getString("password");
        String userType = js.getString("userType");
        Result<String> result = new Result<>();
        if (userService.login(userId,password,userType)) {
            result.setNum("1");
            result.setMessage("登录成功");
            return result;
        }
        else{
            result.setNum("0");
            result.setMessage("登录失败");
            return result;
        }

    }


    /**
     * 用户查询
     *
     * */
    @RequestMapping(value = "/queryById",method = RequestMethod.POST)
    public Result<User> queryByName(@RequestBody JSONObject s){
        String name = s.getString("userId");
        Result<User> result = new Result<>();
        user = userService.quaryByName(name);
        System.out.println(user+" user");
        if (user!=null){
            result.setNum("1");
            result.setMessage("查询成功");
            result.setData(user);
            return result;
        }
        else {
            result.setNum("0");
            result.setMessage("查询失败");
            return  result;
        }
    }

    /**
    *  添加用户
     *  用户注册
    *
    */
    @RequestMapping(value = "/addUser",method = RequestMethod.POST)
    public Result<String> addUser(@RequestBody User user){
        Result<String> result = new Result<>();
        System.out.println(user);
        if (userService.addUser(user)) {
            result.setNum("1");
            result.setMessage("添加成功");
            return result;
        }
        else{
            result.setNum("0");
            result.setMessage("添加失败");
            return  result;
        }

    }

    /**
    * 教师添加考勤记录
     */
    @RequestMapping(value = "/addAttendance",method = RequestMethod.POST)
    public Result<String> addAttendance(@RequestBody AttendanceJob attendanceJob){
        Result<String> result = new Result<>();
        attendanceJob.setAttendanceEnd("1");
        System.out.println("attendanceJob  "+attendanceJob);

            if (userService.addAttendance(attendanceJob)) {  //添加考勤任务

                Result<List<User>> allStuUser = userService.allStudentBleowCourse(attendanceJob.getCourseId());

                List<User> all = allStuUser.getData();

                for (User se : all) {
                    AttendanceRecord aRecord = new AttendanceRecord();
                    aRecord.setAttendanceId(attendanceJob.getAttendanceId().toString());
                    aRecord.setUserId(se.getUserId());
                    aRecord.setAttendanceTime(attendanceJob.getCreateTime());
                    aRecord.setAttendanceState("0");

                    System.out.println(aRecord);   //打印
                    userService.stuAttednance(aRecord);
                }
                result.setNum("1");
                result.setMessage("添加考勤任务成功");
                return result;
            } else {
                result.setNum("0");
                result.setMessage("添加考勤任务失败");
                return result;
            }
    }

    /**
     * 教师结束考勤
     *
     * */
    @RequestMapping(value = "/stopAttendance",method = RequestMethod.POST)
    public Result<String> stopAttendance(@RequestBody JSONObject s){
        Result<String> result = new Result<>();
        String courseId = s.getString("courseId");
        attendanceJob = userService.newAttend(courseId);     //取出该课程下最新的签到记录
        if (attendanceJob.getAttendanceEnd().equals("0")){
            result.setNum("0");
            result.setMessage("没有签到任务发布");
            return result;
        }else{
            userService.stopAttendance(attendanceJob.getCourseId(),attendanceJob.getAttendanceId());
            result.setNum("2");
            result.setMessage("已结束签到");
            return result;
        }
    }


    /**
     * 学生考勤
     * @param  s JSONObject数据
     * */

    @RequestMapping(value = "/stuAttendance",method = RequestMethod.POST)
    public Result<String> stuAttendance(@RequestBody JSONObject s){
        Result<String> result = new Result<>();

        JSONObject number = JSONObject.fromObject(s);
        String num = number.getString("number");//获取签到码

        String js = number.getString("attendanceRecord");     //获取签到学生信息
        System.out.println("js "+js);
        JSONObject Record = JSONObject.fromObject(js);
        timecha.change();                                  // 将json字段中的时间转换为Date时间格式
        AttendanceRecord attendanceRecord =(AttendanceRecord)JSONObject.toBean(Record, AttendanceRecord.class);

        //获取courseId
        String course[] = attendanceRecord.getUserId().split(",");
        String courseId = course[1];
        String userid = course[0];

        attendanceJob = userService.newAttend(courseId);     //取出该课程下最新的签到记录
        System.out.println("attendanceJob   "+attendanceJob);


        if (attendanceJob.getAttendanceEnd().equals("1")){    //签到任务正在进行

            if (num.equals("")){       //签到码为空
                //   System.out.println(num);
                result.setNum("0");
                result.setMessage("请输入签到码");
                return result;
            }

            //判断是否已经签到过
            AttendanceRecord attendanceRecordIs = userService.attendanceRecordIs(attendanceJob.getAttendanceId(),userid);

            if (attendanceRecordIs.getAttendanceState().equals("1")){
                result.setNum("1");
                result.setMessage("你已签到过或老师尚未发布新签到任务");
                return result;
            }

            //数字签到
            if (attendanceRecord.getAttendanceState().equals("1")|| attendanceRecord.getAttendanceState().equals("3")) {
                if (attendanceJob.getAttendanceNumber().equals(num)) {
                    attendanceRecord.setUserId(userid);
                    attendanceRecord.setAttendanceState("1");
                    userService.updateStuAttendance(attendanceRecord,String.valueOf(attendanceJob.getAttendanceId()));
                    result.setNum("1");
                    result.setMessage("签到成功");
                    return result;
                } else {
                    result.setNum("0");
                    result.setMessage("签到码错误");
                    return result;
                }
            }

            //GPS签到
            if (attendanceRecord.getAttendanceState().equals("2")){
                String[] gps1 = num.split(",");       //获取学生位置信息
                double valueX = Double.valueOf(gps1[0]);
                double valueY = Double.valueOf(gps1[1]);
                System.out.println("Student  "+"  X  "+valueX+"  Y  "+valueY);

                String[] gps2 = attendanceJob.getAttendanceNumber().split(",");  //获取老师位置信息
                double valueM = Double.valueOf(gps2[0]);
                double valueN = Double.valueOf(gps2[1]);
                System.out.println("Teacher " + " m " + valueM + " n  " + valueN);
                double dis = gpsDistance.getDistance(valueX, valueY, valueM, valueN);    //计算距离
                System.out.println("dis  "+dis);

                if (dis < 100) {
                    result.setNum("1");
                    result.setMessage("签到成功");
                    attendanceRecord.setAttendanceState("1");
                    attendanceRecord.setUserId(userid);
                    userService.updateStuAttendance(attendanceRecord,String.valueOf(attendanceJob.getAttendanceId()));
                    return result;
                } else {
                    //签到失败
                    result.setNum("0");
                    result.setMessage("签到距离过远");
                    return result;
                }
            }else {
                result.setNum("0");
                result.setMessage("无此签到方式");
                return result;
            }
        }else{
            result.setNum("0");
            result.setMessage("签到已结束或老师未发布签到任务");
            return result;
        }

    }

    /**
     * 最新签到记录
     *
     * */
    @RequestMapping(value = "/newAttendanceJob",method = RequestMethod.POST)
    public Result<AttendanceJob> newAttendanceJob(@RequestBody JSONObject s) {
        Result<AttendanceJob> result = new Result<>();
        attendanceJob = userService.newAttend(s.getString("courseId"));
        result.setData(attendanceJob);
        return result;
    }

    /**
     * 根据课程ID检索课程信息
     *
     * */
    @RequestMapping(value = "/courseMessage",method = RequestMethod.POST)
    public Result<Course> courseMessage(@RequestBody JSONObject s){
        Result<Course> result = new Result<>();
        Integer courseId = Integer.valueOf(s.getString("courseId"));
        course = userService.courseMessage(courseId);
        if (course!=null){
            result.setNum("1");
            result.setMessage("查询成功");
            result.setData(course);
            return result;
        }
        else {
            result.setNum("0");
            result.setMessage("无此课程信息");
            return result;
        }
    }


    /**
     *查询一个课程下的所有学生
     * @param
     * @return
     */
    @PostMapping("/selectAll1")
    public Result<List<User>> selectAllStudentBelowCourse(@RequestBody JSONObject s){
        String name = s.getString("name");
        Result<List<User>> result=userService.selectAllStudentBelowCourse(name);
        return result;
    }

    /**
     * 一个学生在一门课程下的所有签到信息
     */

    @PostMapping("/selectAll3")
    public Result<List<StudentRecord>> selectAllRecordFromOneCourse(@RequestBody JSONObject s){
        String userId=s.getString("userId");
        String courseId = s.getString("courseId");
        Result<List<StudentRecord>> result=userService.selectAllRecordFromOneCourse(userId, courseId);
        return result;
    }

    /**
     * 一门课程下老师发布的签到记录
     */
    @PostMapping("/selectAll4")
    public Result<List<AttendanceJob>> selectAllAttendanceJob(@RequestBody JSONObject s){
       // Integer courseId = Integer.valueOf(s.getString("courseId"));
        String courseId = s.getString("courseId");
        Result<List<AttendanceJob>> result=userService.selectAllAttendanceJob(courseId);
        return result;
    }

    /**
     * 教师某次的发布的签到记录下的学生的信息
     */
    @PostMapping("/selectAll5")
    Result<List<StudentStatus>> selectAllRecordFromCourse(@RequestBody JSONObject s){
        String attendanceId=s.getString("attendanceId");
        Result<List<StudentStatus>> result=userService.selectAllRecordFromCourse(attendanceId);
        System.out.println("Result  "+result);
        return result;
    }


}
